package com.txby.platformCore.component.util;

import java.util.ArrayList;
import java.util.List;

import com.gexin.fastjson.JSON;

import net.sf.json.JSONArray;

public class TreeUtil {

	List<TreeNode> TreeNodes = new ArrayList<>();

	public String buildTree(List<TreeNode> TreeNodes) {

		TreeUtil treeBuilder = new TreeUtil(TreeNodes);

		return treeBuilder.buildJSONTree();
	}

	public TreeUtil() {
	}

	public TreeUtil(List<TreeNode> TreeNodes) {
		super();
		this.TreeNodes = TreeNodes;
	}

	// 构建JSON树形结构
	public String buildJSONTree() {
		List<TreeNode> TreeNodeTree = buildTree();
/*		JSONArray jsonArray = JSONArray.fromObject(TreeNodeTree);
		return jsonArray.toString();
		JSONArray jsonArray = JSONArray.fromObject(TreeNodeTree);*/
		return JSON.toJSONString(TreeNodeTree);
	}

	// 构建树形结构
	public List<TreeNode> buildTree() {
		List<TreeNode> s = new ArrayList<>();
		List<TreeNode> rootTreeNodes = getRootTreeNodes();
		for (TreeNode rootTreeNode : rootTreeNodes) {
			buildChildTreeNodes(rootTreeNode);
			s.add(rootTreeNode);
		}
		return s;
	}

	// 递归子节点
	public void buildChildTreeNodes(TreeNode TreeNode) {
		List<TreeNode> children = getChildTreeNodes(TreeNode);
		if (!children.isEmpty()) {
			for (TreeNode child : children) {
				buildChildTreeNodes(child);
			}
			TreeNode.setChildren(children);
		}
	}

	// 获取父节点下所有的子节点
	public List<TreeNode> getChildTreeNodes(TreeNode pTreeNode) {
		List<TreeNode> childTreeNodes = new ArrayList<>();
		for (TreeNode n : TreeNodes) {
			if (pTreeNode.getId().equals(n.getPId())) {
				childTreeNodes.add(n);
			}
		}
		return childTreeNodes;
	}

	// 判断是否为根节点
	public boolean rootTreeNode(TreeNode TreeNode) {
		boolean isRootTreeNode = true;
		for (TreeNode n : TreeNodes) {
			if (TreeNode.getPId().equals(n.getId())) {
				isRootTreeNode = false;
				break;
			}
		}
		return isRootTreeNode;
	}

	// 获取集合中所有的根节点
	public List<TreeNode> getRootTreeNodes() {
		List<TreeNode> rootTreeNodes = new ArrayList<>();
		for (TreeNode n : TreeNodes) {
			if (rootTreeNode(n)) {
				rootTreeNodes.add(n);
			}
		}
		return rootTreeNodes;
	}

}
